package pers.xhh.shopapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pers.xhh.shopapi.common.Constant;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiGoodsDao;
import pers.xhh.shopapi.entity.*;
import pers.xhh.shopapi.entity.to.goods.MiGoodsComTo;
import pers.xhh.shopapi.entity.to.goods.MiGoodsTo;
import pers.xhh.shopapi.entity.vo.goods.MiGoodsPutVo;
import pers.xhh.shopapi.entity.vo.goods.MiGoodsVo;
import pers.xhh.shopapi.service.*;
import pers.xhh.shopapi.util.DateUtils;
import pers.xhh.shopapi.util.FileUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiGoodsServiceImpl extends ServiceImpl<MiGoodsDao, MiGoodsEntity> implements MiGoodsService {

    @Autowired
    MiAttributeService miAttributeService;

    @Autowired
    MiGoodsAttrService miGoodsAttrService;

    @Autowired
    MiGoodsPicsService miGoodsPicsService;

    @Autowired
    MiWareService miWareService;

    @Override
    public Mi listGoods(String query, Integer pagenum, Integer pagesize) {
        if (pagenum == null || pagesize == null) {
            return Mi.error(ResultCode.ERROR303.getMessage(), ResultCode.ERROR303.getStatus());
        }
        if (pagenum <= 0 || pagesize <= 0) {
            return Mi.error(ResultCode.ERROR304.getMessage(), ResultCode.ERROR304.getStatus());
        }

        // ->查询
        Page<MiGoodsEntity> page = new Page<>(pagenum, pagesize);
        QueryWrapper<MiGoodsEntity> queryWrapper = new QueryWrapper<>();
        if (query != null) {
            queryWrapper = new QueryWrapper<MiGoodsEntity>()
                    .like("goods_name", query);
        }
        this.page(page, queryWrapper);

        // —>结果
        List<MiGoodsEntity> records = page.getRecords();

        if (records.size() > 0) {
            List<MiGoodsVo> collect = records.stream().map(item -> {
                MiGoodsVo miGoodsVo = new MiGoodsVo();
                miGoodsVo.setCat_id(item.getCatId());
                miGoodsVo.setCat_one_id(item.getCatOneId());
                miGoodsVo.setCat_two_id(item.getCatTwoId());
                miGoodsVo.setCat_three_id(item.getCatThreeId());
                miGoodsVo.setGoods_id(item.getGoodsId());
                miGoodsVo.setGoods_introduce(item.getGoodsIntroduce());
                miGoodsVo.setGoods_name(item.getGoodsName());
                miGoodsVo.setGoods_number(item.getGoodsNumber());
                miGoodsVo.setGoods_price(item.getGoodsPrice());
                miGoodsVo.setGoods_weight(item.getGoodsWeight());
                miGoodsVo.setGoods_state(item.getGoodsState());
                miGoodsVo.setIs_promote(item.getIsPromote() == 1);
                miGoodsVo.setAdd_time(DateUtils.formatDate(item.getCreateTime()));
                // 查询attr
                List<MiGoodsAttrEntity> goods_id =
                        miGoodsAttrService.list(new QueryWrapper<MiGoodsAttrEntity>().eq("goods_id", item.getGoodsId()));
                // 根据属性id查询属性名
                for (MiGoodsAttrEntity miGoodsAttrEntity : goods_id) {
                    Integer attrId = miGoodsAttrEntity.getAttrId();
                    MiAttributeEntity byId = miAttributeService.getById(attrId);
                    if(byId != null){
                        miGoodsAttrEntity.setAttrName(byId.getAttrName());
                    }
                }
                miGoodsVo.setAttrs(goods_id);
                return miGoodsVo;
            }).collect(Collectors.toList());
            long total = page.getTotal();
            long current = page.getCurrent();
            Map<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("pagenum", current);
            map.put("goods", collect);

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }


        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi saveGoods(MiGoodsTo miGoodsTo) {
        String goodsName = miGoodsTo.getGoods_name();
        String goodsCat = miGoodsTo.getGoods_cat();
        BigDecimal goodsPrice = miGoodsTo.getGoods_price();
        if (goodsPrice == null) {
            goodsPrice = BigDecimal.valueOf(0L);
        }
        Integer goodsNumber = Integer.parseInt(miGoodsTo.getGoods_number());
        Integer goodsWeight = Integer.parseInt(miGoodsTo.getGoods_weight());

        MiGoodsEntity goodsEntity = new MiGoodsEntity();
        goodsEntity.setGoodsName(goodsName);
        String[] split = goodsCat.split(",");
        if (split.length != Constant.ATTR_LIST_LENGTH) {
            return Mi.error(ResultCode.ERROR601.getMessage(), ResultCode.ERROR601.getStatus());
        }
        // 保存商品是，该商品必须是三级分类下的商品
        goodsEntity.setCatId(Integer.parseInt(split[2]));
        goodsEntity.setCatOneId(Integer.parseInt(split[0]));
        goodsEntity.setCatTwoId(Integer.parseInt(split[1]));
        goodsEntity.setCatThreeId(Integer.parseInt(split[2]));
        goodsEntity.setGoodsPrice(goodsPrice);
        goodsEntity.setGoodsNumber(goodsNumber);
        goodsEntity.setGoodsWeight(goodsWeight);
        goodsEntity.setCreateTime(new Date());
        goodsEntity.setUpdateTime(new Date());
        String goodsIntroduce = miGoodsTo.getGoods_introduce();
        if (goodsIntroduce != null) {
            goodsEntity.setGoodsIntroduce(goodsIntroduce);
        }
        boolean save = this.save(goodsEntity);
        if(save){
            // 如果保存成功,获取保存成功的id
            Integer goodsId = goodsEntity.getGoodsId();
            // 如果pics数组不为空,保存到mi_goods_pics
            List<MiGoodsTo.Pics> pics = miGoodsTo.getPics();
            if (pics != null && pics.size() > 0) {
                for (MiGoodsTo.Pics pic : pics) {
                    // ->保存到mi_goods_pics
                    String picAddress = pic.getPic();
                    MiGoodsPicsEntity miGoodsPicsEntity = new MiGoodsPicsEntity();
                    miGoodsPicsEntity.setGoodsId(goodsId);
                    miGoodsPicsEntity.setPicsBig(picAddress);
                    miGoodsPicsEntity.setPicsMid(picAddress);
                    miGoodsPicsEntity.setPicsSma(picAddress);
                    miGoodsPicsEntity.setUpdateTime(new Date());
                    miGoodsPicsEntity.setCreateTime(new Date());
                    miGoodsPicsService.save(miGoodsPicsEntity);
                }
            }

            // 如果attrs数据不为空,前端过来也一定不为空
            List<MiGoodsTo.GoodsAttrs> attrs = miGoodsTo.getAttrs();
            if (attrs != null && attrs.size() > 0) {
                for (MiGoodsTo.GoodsAttrs attr : attrs) {
                    // ->保存到mi_goods_attrs
                    Integer attrId = attr.getAttr_id();
                    String attrValue = attr.getAttr_value();
                    MiGoodsAttrEntity miGoodsAttrEntity = new MiGoodsAttrEntity();
                    miGoodsAttrEntity.setGoodsId(goodsId);
                    miGoodsAttrEntity.setAttrId(attrId);
                    miGoodsAttrEntity.setAttrValue(attrValue);
                    miGoodsAttrEntity.setCreateTime(new Date());
                    miGoodsAttrEntity.setUpdateTime(new Date());
                    miGoodsAttrService.save(miGoodsAttrEntity);
                }
            }

            // 保存库存
            MiWareEntity miWareEntity = new MiWareEntity();
            miWareEntity.setCreateTime(new Date());
            miWareEntity.setUpdateTime(new Date());
            miWareEntity.setGoodsId(goodsId);
            miWareEntity.setGoodsTitle(goodsEntity.getGoodsName());
            miWareEntity.setStock(goodsEntity.getGoodsNumber());
            miWareEntity.setStockLocked(0);
            miWareService.save(miWareEntity);

            return Mi.ok(ResultCode.SUCCESS1.getMessage(), ResultCode.SUCCESS1.getStatus(), "保存成功");
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi getGoodsById(Integer id) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        MiGoodsEntity byId = this.getById(id);
        if(byId != null){
            MiGoodsPutVo miGoodsVo = new MiGoodsPutVo();
            miGoodsVo.setCat_id(byId.getCatId());
            miGoodsVo.setCat_one_id(byId.getCatOneId());
            miGoodsVo.setCat_two_id(byId.getCatTwoId());
            miGoodsVo.setCat_three_id(byId.getCatThreeId());
            miGoodsVo.setGoods_id(byId.getGoodsId());
            miGoodsVo.setGoods_introduce(byId.getGoodsIntroduce());
            miGoodsVo.setGoods_name(byId.getGoodsName());
            miGoodsVo.setGoods_number(byId.getGoodsNumber());
            miGoodsVo.setGoods_price(byId.getGoodsPrice());
            miGoodsVo.setGoods_weight(byId.getGoodsWeight());
            miGoodsVo.setGoods_state(byId.getGoodsState());
            miGoodsVo.setIs_promote(byId.getIsPromote() == 1);
            miGoodsVo.setAdd_time(DateUtils.formatDate(byId.getCreateTime()));

            // 查询pics
            List<MiGoodsPicsEntity> miGoodsPicsEntityList =
                    miGoodsPicsService.list(new QueryWrapper<MiGoodsPicsEntity>().eq("goods_id", id));
            if(miGoodsPicsEntityList != null && miGoodsPicsEntityList.size() > 0){
                List<MiGoodsTo.Pics> collect = miGoodsPicsEntityList.stream().map(item -> {
                    MiGoodsTo.Pics pics = new MiGoodsTo.Pics();
                    pics.setPic(item.getPicsBig());
                    return pics;
                }).collect(Collectors.toList());
                miGoodsVo.setPics(collect);
            }

            // 查询attrs
            List<MiGoodsAttrEntity> miGoodsAttrEntityList =
                    miGoodsAttrService.list(new QueryWrapper<MiGoodsAttrEntity>().eq("goods_id", id));
            if(miGoodsAttrEntityList != null && miGoodsAttrEntityList.size() > 0){
                List<Map<String, Object>> collect = miGoodsAttrEntityList.stream().map(item -> {
                    MiAttributeEntity miAttributeEntity =
                            miAttributeService.getById(item.getAttrId());
                    Map<String, Object> map = new HashMap<>();
                    if(miAttributeEntity != null){
                        map.put("goods_id", id);
                        map.put("attr_id", item.getAttrId());
                        map.put("attr_value", item.getAttrValue());
                        map.put("attr_name", miAttributeEntity.getAttrName());
                        map.put("attr_sel", miAttributeEntity.getAttrSel());
                        map.put("attr_write", miAttributeEntity.getAttrWrite());
                        map.put("attr_vals", miAttributeEntity.getAttrVals());
                    }
                    return map;
                }).collect(Collectors.toList());
                miGoodsVo.setAttrs(collect);
            }

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), miGoodsVo);
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi updateGoodsById(Integer id, MiGoodsTo miGoodsTo) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }
        // TODO 此更新可以和保存合并
        String goodsName = miGoodsTo.getGoods_name();
        String goodsCat = miGoodsTo.getGoods_cat();
        BigDecimal goodsPrice = miGoodsTo.getGoods_price();
        if (goodsPrice == null) {
            goodsPrice = BigDecimal.valueOf(0L);
        }
        Integer goodsNumber = Integer.parseInt(miGoodsTo.getGoods_number());
        Integer goodsWeight = Integer.parseInt(miGoodsTo.getGoods_weight());

        MiGoodsEntity goodsEntity = new MiGoodsEntity();
        goodsEntity.setGoodsId(id);
        goodsEntity.setGoodsName(goodsName);
        String[] split = goodsCat.split(",");
        if (split.length != Constant.ATTR_LIST_LENGTH) {
            return Mi.error(ResultCode.ERROR601.getMessage(), ResultCode.ERROR601.getStatus());
        }
        // 更新商品是，该商品必须是三级分类下的商品
        goodsEntity.setCatId(Integer.parseInt(split[2]));
        goodsEntity.setCatOneId(Integer.parseInt(split[0]));
        goodsEntity.setCatTwoId(Integer.parseInt(split[1]));
        goodsEntity.setCatThreeId(Integer.parseInt(split[2]));
        goodsEntity.setGoodsPrice(goodsPrice);
        goodsEntity.setGoodsNumber(goodsNumber);
        goodsEntity.setGoodsWeight(goodsWeight);
        goodsEntity.setCreateTime(new Date());
        goodsEntity.setUpdateTime(new Date());
        String goodsIntroduce = miGoodsTo.getGoods_introduce();
        if (goodsIntroduce != null) {
            goodsEntity.setGoodsIntroduce(goodsIntroduce);
        }
        boolean update = this.updateById(goodsEntity);
        if(update){
            // 如果保存成功,获取保存成功的id
            Integer goodsId = goodsEntity.getGoodsId();
            // 如果pics数组不为空,保存到mi_goods_pics
            List<MiGoodsTo.Pics> pics = miGoodsTo.getPics();
            if (pics != null && pics.size() > 0) {
                for (MiGoodsTo.Pics pic : pics) {
                    // ->更新到mi_goods_pics
                    String picAddress = pic.getPic();
                    MiGoodsPicsEntity miGoodsPicsEntity = new MiGoodsPicsEntity();
                    miGoodsPicsEntity.setGoodsId(goodsId);
                    miGoodsPicsEntity.setPicsBig(picAddress);
                    miGoodsPicsEntity.setPicsMid(picAddress);
                    miGoodsPicsEntity.setPicsSma(picAddress);
                    miGoodsPicsEntity.setUpdateTime(new Date());
                    miGoodsPicsEntity.setCreateTime(new Date());
                    miGoodsPicsService.update(miGoodsPicsEntity,
                            new QueryWrapper<MiGoodsPicsEntity>().eq("goods_id", id));
                }
            }

            // 如果attrs数据不为空,前端过来也一定不为空
            List<MiGoodsTo.GoodsAttrs> attrs = miGoodsTo.getAttrs();
            if (attrs != null && attrs.size() > 0) {
                for (MiGoodsTo.GoodsAttrs attr : attrs) {
                    // ->更新到mi_goods_attrs
                    Integer attrId = attr.getAttr_id();
                    String attrValue = attr.getAttr_value();
                    MiGoodsAttrEntity miGoodsAttrEntity = new MiGoodsAttrEntity();
                    miGoodsAttrEntity.setGoodsId(goodsId);
                    miGoodsAttrEntity.setAttrId(attrId);
                    miGoodsAttrEntity.setAttrValue(attrValue);
                    miGoodsAttrEntity.setUpdateTime(new Date());
                    miGoodsAttrService.update(miGoodsAttrEntity,
                            new QueryWrapper<MiGoodsAttrEntity>().eq("id", attrId));
                }
            }
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), "更新成功");
        } else {
            System.out.println("更新失败");
            return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
        }


    }

    @Override
    public Mi deleteById(Integer id) {

        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }
        boolean b = this.removeById(id);
        if(b){
            // 删除pics
            boolean deletePics = miGoodsPicsService.remove(new QueryWrapper<MiGoodsPicsEntity>().eq("goods_id", id));

            // 删除attr
            boolean deleteAttr = miGoodsAttrService.remove(new QueryWrapper<MiGoodsAttrEntity>().eq("goods_id", id));

            // 删除ware
            boolean deleteWare = miWareService.remove(new QueryWrapper<MiWareEntity>().eq("goods_id", id));

            if(deletePics && deleteAttr && deleteWare){
                return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), "删除成功");
            }
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi uploadFilePic(MultipartFile file) {
        try {
//            String property = System.getProperty("user.dir") + File.separator + "src" +
//                    File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator;
            //将图片写入 sharePath
            String pathName = System.getProperty("catalina.home") + "/webapps/sharePath/";
            String fileName = UUID.randomUUID().toString().replace("-", "");
            String name = fileName + ".png";
            boolean b = FileUtil.writeFile(file.getInputStream(), pathName + name);
            if(b){
                Map<String, Object> map = new HashMap<>();
                map.put("tmp_path", name);
                map.put("url", "http://127.0.0.1:8088/sharePath/" + name);
                return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi commonUpdate(Integer id, MiGoodsComTo miGoodsTo) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }
        MiGoodsEntity miGoodsEntity = new MiGoodsEntity();
        miGoodsEntity.setGoodsId(id);
        String goods_name = miGoodsTo.getGoods_name();
        String goods_number = miGoodsTo.getGoods_number();
        BigDecimal goods_price = miGoodsTo.getGoods_price();
        String goods_weight = miGoodsTo.getGoods_weight();

        if(goods_name != null){
            miGoodsEntity.setGoodsName(goods_name);
        }
        if(goods_number != null){
            miGoodsEntity.setGoodsNumber(Integer.parseInt(goods_number));
        }
        if(goods_price != null){
            miGoodsEntity.setGoodsPrice(goods_price);
        }
        if(goods_weight != null){
            miGoodsEntity.setGoodsWeight(Integer.parseInt(goods_weight));
        }

        boolean b = this.updateById(miGoodsEntity);
        if(b){
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), "更新成功！");
        }
        return Mi.error(ResultCode.ERROR1004.getMessage(), ResultCode.ERROR1004.getStatus());
    }
}
